/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */

package tools;

import com.google.android.gcm.server.Message;
import com.google.android.gcm.server.MulticastResult;
import com.google.android.gcm.server.Sender;
import com.openbrew.openbrewrf.Gcm;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.persistence.EntityManager;
import javax.persistence.TypedQuery;
import service.APKFileFacadeREST;

/**
 *
 * @author chapmand
 */
public class GCMTools {

    private static final String GOOGLE_SERVER_KEY = "AIzaSyBmU1lXaVj9tBggR890XDT5s5LNNk4q5Fw";
    static final String MESSAGE_KEY = "message";
    static final String APK_FILE_UPDATE = "APK_File_Updated";
    
    public String doNewAPKFileNotification(final EntityManager em){
        Sender sender = new Sender(GOOGLE_SERVER_KEY);
        Message message = new Message.Builder().timeToLive(30)
            .delayWhileIdle(false).addData(MESSAGE_KEY, APK_FILE_UPDATE).build();
        List<String> regIds = getRefIDs(em);
        try {
            MulticastResult result = sender.send(message, regIds, 1);
            return result.toString();
        } catch (IOException ex) {
            Logger.getLogger(APKFileFacadeREST.class.getName()).log(Level.SEVERE, null, ex);
        }
        return "Error Occured!";
    }
    
    /***************************************************************************
     * Ref ID List Function.
     **************************************************************************/
    private List<String> getRefIDs(final EntityManager en){
        TypedQuery<Gcm> query = en.createQuery(
            "SELECT g FROM Gcm g", Gcm.class);
        List<Gcm> gcms = query.getResultList();
        List<String> refids = new ArrayList<String>();
        for(Gcm gcm : gcms){
            refids.add(gcm.getRegid());
        }
        return refids;
    }
    
}
